package com.socket.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class SocketServer {
    BufferedWriter writer;
    BufferedReader reader;

    public static void main(String[] args) {

        SocketServer socketServer = new SocketServer();
        socketServer.startServer();

    }

    public void startServer() {

        BufferedReader reader = null;
        ServerSocket serverSocket = null;
        Socket socket = null;
        writer = null;
        try {
            serverSocket = new ServerSocket(8000);
            System.out.println("sever started");
            while (true) {
                socket = serverSocket.accept(); //服务端和客户端建立的连接
                manageConnection(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void manageConnection(final Socket socket) {
        new Thread(() -> {
            try {
                System.out.println("client " + socket.hashCode() + " connected");
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String receiveMsg;
                writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                while ((receiveMsg = reader.readLine()) != null) {
                    System.out.println("client:" +socket.hashCode() +":"+ receiveMsg);
                    writer.write("server reply:" + receiveMsg + "\n");
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    writer.close();
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
}
